package com.wuye.service;

import com.wuye.web.*;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.logging.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;

import com.wuye.repository.*;
import com.wuye.model.*;

@Service
public class OrderService {
    private Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderItemRepository orderItemRepository;
    @Autowired
    private MenuActivityRepository menuActivityRepository;
    @Autowired
    private UserRepository userRepository;

    public List<Order> getDayBook() {
        return orderRepository.findAllByOrderByOrderDate_Desc();
    }

    public void updateOrder(String orderNum) {
        Order order = orderRepository.findByOrderNum(orderNum);
        order.setOrderState("COMPLETE");
        orderRepository.save(order);
    }

    public void updateOrderCancel(String orderNum) {
        Order order = orderRepository.findByOrderNum(orderNum);
        List<OrderItem> lists = orderItemRepository.findByOrderSn(orderNum);
        for(OrderItem om : lists){
            String menuId = om.getMenuId();
            int amout = om.getAmount();
            MenuActivity ma = menuActivityRepository.findByMenuId(menuId);
            Integer aa = ma.getStoreNum();
            if(aa==null) aa = 0;
            ma.setStoreNum(aa+amout);
            menuActivityRepository.save(ma);
        }
        order.setOrderState("RESTAURANT_CANCEL");
        orderRepository.save(order);
    }

    @Transactional(rollbackFor = {Exception.class})
    public JSONObject createOrder(String userId, String cellPhone, String userName, String payMethod, Float totalPrice, List<ShoppingCartItem> cartItems, String memo) {
        if (!(cartItems.size() > 0)) {
            return ST.orderNoProductDate.getJsonObject();
        }
        PayMethod payWay = PayMethod.findByName(payMethod);
        if (null == payWay) {
            return ST.orderPayBillWayNotDefine.getJsonObject();
        }
        OrderState orderState = OrderState.CONFIRM;
        if (PayMethod.SKY.equals(payWay)) {
            orderState = OrderState.CONFIRM;
        } else if (PayMethod.WEIXIN.equals(payWay)) {
            orderState = OrderState.UN_CONFIRM;
        }

        Date now = new Date();
        String r = String.valueOf(System.nanoTime());
        String orderSn = Constant.sdfNumber2.format(now) + r.substring(r.length() - 3);
        Order order = new Order();
        order.setOrderNum(orderSn);
        order.setUserId(userId);
        order.setCellPhone(cellPhone);
        order.setUserName(userName);
        order.setOrderDate(now);
        order.setOrderState(orderState.toString());
        order.setTotalPrice(totalPrice);
        order.setPayMethod(payWay.toString());

        order.setMemo(memo);
        orderRepository.save(order);
        List<OrderItem> orderItems = new ArrayList<OrderItem>();
        for (ShoppingCartItem item : cartItems) {
            OrderItem i = new OrderItem();
            i.setItemId(orderSn + "-" + item.getMenuId());
            i.setOrderNum(orderSn);
            i.setMenuId(item.getMenuId());
            i.setItemName(item.getItemName());
            i.setItemPrice(item.getItemPrice());
            i.setAmount(item.getNum());
            orderItems.add(i);
        }
        orderItemRepository.save(orderItems);

        JSONObject json = ST.ok.getJsonObject();
        json.put("orderSn", orderSn);
        json.put("orderState", orderState.toString());
        json.put("payMethod", payMethod.toString());
        return json;
    }

    public List<OrderDetail> findAllOrderList(String userId) {
        List<Order> orders = orderRepository.findByUserIdOrderByOrderDate_Desc(userId);
        List<OrderDetail> lists = comm(orders);
        return lists;
    }

    public List<OrderDetail> getAllOrderList() throws Exception {
        List<Order> orders = orderRepository.findAllByOrderByOrderDate_Desc();
        List<OrderDetail> lists = comm(orders);
        return lists;
    }

    @Transactional(rollbackFor = {Exception.class})
    public List<OrderDetail> getAllOrderListss(String dateTime, String endTime, String orderStatus) throws Exception {
        List<Order> orders = new ArrayList<Order>();
        if (StringUtils.isBlank(dateTime) && StringUtils.isBlank(orderStatus) && StringUtils.isBlank(endTime)) {
            orders = orderRepository.findOrderByOrderDate_Desc();
            List<OrderDetail> detail = comm(orders);
            log.info("begin of /orderService/getAllOrderListss");
            log.info(detail);
            log.info("end of /orderService/getAllOrderListss");
            return detail;
        }
        if (StringUtils.isBlank(endTime)) {
            if (StringUtils.isBlank(dateTime) && "1".equals(orderStatus)) {
                orders = orderRepository.findsAllOrders();
                return comm(orders);
            }
            if (StringUtils.isBlank(dateTime) && !"1".equals(orderStatus)) {
                String stu = convertStatus(orderStatus);
                orders = orderRepository.findsByOrderStatus(stu);
                return comm(orders);
            }
            if (StringUtils.isNotBlank(dateTime) && "1".equals(orderStatus)) {
                orders = orderRepository.findOrderByOrderDate(dateTime);
                return comm(orders);
            }
            if (StringUtils.isNotBlank(dateTime) && !"1".equals(orderStatus)) {
                String stu = convertStatus(orderStatus);
                orders = orderRepository.findAllOrders(dateTime, stu);
                return comm(orders);
            }
        } else {
            if (StringUtils.isBlank(dateTime) && "1".equals(orderStatus)) {
                //查询截止日期内的所有订单
                orders = orderRepository.findAllByEndtime(endTime);
                return comm(orders);
            }
            if (StringUtils.isBlank(dateTime) && !"1".equals(orderStatus)) {
                //根据订单状态查询截止日期内的订单
                String stu = convertStatus(orderStatus);
                orders = orderRepository.findAllByEndtimeAndStatus(endTime, stu);
                return comm(orders);
            }
            if (StringUtils.isNotBlank(dateTime) && "1".equals(orderStatus)) {
                //查询起始时间到截止时间内的所有订单
                orders = orderRepository.findAllByStarttimeAndEndtime(dateTime, endTime);
                return comm(orders);
            }
            if (StringUtils.isNotBlank(dateTime) && !"1".equals(orderStatus)) {
                //根据订单状态查询起始时间到截止时间内的订单
                String stu = convertStatus(orderStatus);
                orders = orderRepository.findAllByStarttimeAndEndtimeAndState(dateTime, endTime, stu);
                return comm(orders);
            }
        }
        return null;
    }

    public List<OrderDetail> comm(List<Order> orders) {
        List<OrderDetail> ods = new ArrayList<OrderDetail>();
        for (Order o : orders) {
            OrderDetail od = new OrderDetail(o);
            List<OrderItem> orderItems = orderItemRepository.findByOrderSn(o.getOrderNum());
            od.setOrderItems(orderItems);
            ods.add(od);
        }
        return ods;
    }

    //查询订单状态
    public List<String> findOrderState() {
        List<String> str = new ArrayList<String>();
        for (OrderState ord : OrderState.values()) {
            str.add(ord.getState());
        }
        return str;
    }

    //转换订单状态
    public String convertStatus(String sta) {
        for (OrderState o : OrderState.values()) {
            if (o.getState().equals(sta)) return o.toString();
        }
        return "1";
    }
    //根据订单id查询订单状态
    public Order queryOrderStatus(String orderId){
        Order order = orderRepository.findOne(orderId);
        return order;
    }

    //退款状态更改为已退款
    public void refundOrder(String orderNum){
        Order order = orderRepository.findOne(orderNum);
        order.setOrderState(OrderState.CANCEL.toString());
        orderRepository.save(order);
    }
    /**
     * 微信支付回调完成订单
     *
     * @param sn
     * @param trade_no
     * @param trade_status
     * @param payName
     * @return
     */
    public Order doOrder(String sn, String trade_no, String trade_status, String payName) {
        if (trade_status.indexOf("SUCCESS") < 0) {
            log.error("状态有误:" + sn + ";trade_no=" + trade_no + ";trade_status=" + trade_status);
            return null;
        }
        Order order = orderRepository.findByOrderNum(sn);
        if (order != null) {
            if (order.getOrderState().toString().equals(OrderState.UN_CONFIRM.toString())) {
                order.setOrderState(OrderState.CONFIRM.toString());
                orderRepository.save(order);
            } else {
                log.error("订单已支付或者没有待付款订单!!!!!!!!!");
            }
        } else {
            log.error("订单号不存在，有可能来测试系统，但支付成功!!!!!!!!!!sn=" + sn + ";trade_no=" + trade_no + ";trade_status=" + trade_status);
        }
        return order;
    }
}